package com.sugar.follow.up.module.business.service.config;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sugar.follow.up.module.business.controller.app.config.vo.AppBasicConfigRespVO;
import com.sugar.follow.up.module.business.enums.config.ConfigEnum;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import com.sugar.follow.up.module.business.controller.admin.config.vo.*;
import com.sugar.follow.up.module.business.dal.dataobject.config.BizConfigDO;
import com.sugar.follow.up.framework.common.pojo.PageResult;
import com.sugar.follow.up.framework.common.pojo.PageParam;
import com.sugar.follow.up.framework.common.util.object.BeanUtils;

import com.sugar.follow.up.module.business.dal.mysql.config.BizConfigMapper;

import static com.sugar.follow.up.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.follow.up.framework.common.util.collection.CollectionUtils.convertList;
import static com.sugar.follow.up.framework.common.util.collection.CollectionUtils.diffList;
import static com.sugar.follow.up.module.business.enums.ErrorCodeConstants.*;
import static com.sugar.follow.up.module.business.enums.config.ConfigEnum.*;

/**
 * 参数配置 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class BizConfigServiceImpl implements BizConfigService {

    @Resource
    private BizConfigMapper bizConfigMapper;


    @Override
    public void updateBizConfig(BizConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateBizConfigExists(updateReqVO.getId());
        // 更新
        BizConfigDO updateObj = BeanUtils.toBean(updateReqVO, BizConfigDO.class, o -> {
            if (HOME_BANNER_IMAGES.getValue().equals(o.getConfigKey())) {
                o.setValue(String.join(",", (List<String>) updateReqVO.getValue()));
            } else
                o.setValue(String.valueOf(updateReqVO.getValue()));
        });
        bizConfigMapper.updateById(updateObj);
    }

    private void validateBizConfigExists(Long id) {
        if (bizConfigMapper.selectById(id) == null) {
            throw exception(BIZ_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public BizConfigDO getBizConfig(Long id) {
        return bizConfigMapper.selectById(id);
    }

    @Override
    public PageResult<BizConfigDO> getBizConfigPage(BizConfigPageReqVO pageReqVO) {
        return bizConfigMapper.selectPage(pageReqVO);
    }

    @Override
    public <T> T getBizConfigByKey(ConfigEnum configEnum, Class<T> cls) {
        BizConfigDO config = bizConfigMapper.selectOne(BizConfigDO::getConfigKey, configEnum.getValue());
        if (Objects.isNull(config))
            throw exception(BIZ_CONFIG_NOT_EXISTS);

        return cn.hutool.core.convert.Convert.convert(cls, config.getValue());
    }

    @Override
    public <K, T> Map<K, T> getBizConfigMapByKeys(Class<K> kCls, Class<T> cls, ConfigEnum... configEnums) {
        List<BizConfigDO> bizConfigs = bizConfigMapper.selectList(Wrappers.<BizConfigDO>lambdaQuery()
                .in(BizConfigDO::getConfigKey, Arrays.stream(configEnums).map(ConfigEnum::getValue).collect(Collectors.toList())));
        return bizConfigs
                .stream()
                .collect(Collectors
                        .groupingBy(o -> kCls.equals(ConfigEnum.class) ? kCls.cast(ConfigEnum.find(o.getConfigKey())) : kCls.cast(o.getConfigKey()),
                                Collectors.mapping(BizConfigDO::getValue,
                                        Collectors.collectingAndThen(Collectors.toList(),
                                                list -> list.isEmpty() ? null : cn.hutool.core.convert.Convert.convert(cls, list.get(0))))));
    }

    // ======================================== APP 接口 ========================================

    @Override
    public AppBasicConfigRespVO getBizConfigBasic() {
        Map<ConfigEnum, String> configMap = this.getBizConfigMapByKeys(ConfigEnum.class, String.class,
                PROJECT_NAME,
                PROJECT_LOGO,
                USER_PRIVACY_AGREEMENT,
                USER_SERVICE_AGREEMENT,
                DEPARTMENT_INTRODUCTION,
                OFFICIAL_ACCOUNT_QR_CODE,
                HOME_BANNER_IMAGES,
                SERVICE_MOBILE);

        AppBasicConfigRespVO respVO = new AppBasicConfigRespVO();

        respVO.setLogo(configMap.get(PROJECT_LOGO));
        respVO.setName(configMap.get(PROJECT_NAME));
        respVO.setUserPrivacyAgreement(configMap.get(USER_PRIVACY_AGREEMENT));
        respVO.setUserServiceAgreement(configMap.get(USER_SERVICE_AGREEMENT));
        respVO.setDepartmentIntroduction(configMap.get(DEPARTMENT_INTRODUCTION));
        respVO.setOfficialAccountQrCode(configMap.get(OFFICIAL_ACCOUNT_QR_CODE));
        respVO.setHomeBannerImages(configMap.get(HOME_BANNER_IMAGES).split(","));
        respVO.setServiceMobile(configMap.get(SERVICE_MOBILE));

        return respVO;
    }
}